<template>
  <div class="home">
    <!-- 搜索框 -->
    <Search v-model="searchKeyword" placeholder="请输入考试名称" show-action @search="onSearch" />

    <!-- 考试列表 -->
    <div class="exam-list">
      <!-- 使用 v-for 循环渲染每个考试项 -->
      <Cell
          v-for="exam in filteredExams"
          :key="exam.id"
          :class="{ title: true }"
          :title="exam.title"
          @click="goToDetail(exam)"
          style="font-size: 12px"
          is-link
      >
        <!-- 在 Cell 组件内部添加删除按钮 -->
        <div class="delete-wrapper" v-if="Local.get('userInfo').role === 0 || Local.get('userInfo').role === 1">
          <img @click.stop="confirmDelete(exam.id)"
          src="../../assets/icons/delete.png"
          class="delete-icon"
          alt="删除"
          />
        </div>
      </Cell>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import axios from 'axios'; // 引入axios
import {Dialog,Cell, Search} from 'vant';
import {Local} from "@/utils/storage"; // 引入vant组件

// 定义搜索关键词
const searchKeyword = ref('');

// 定义路由
const router = useRouter();

// 定义考试数据
const exams = ref([]);

// 定义fetchExams函数
const fetchExams = async () => {
  try {
    const response = await axios.get('/api/exams/list');
    exams.value = response.data;
  } catch (error) {
    console.error('An error occurred:', error);
  }
};

// Define route
const route = useRoute();

onMounted(() => {
  fetchExams();
});

// 计算属性：根据搜索关键词过滤考试列表
const filteredExams = computed(() => {
  return exams.value.filter(exam => exam.title.includes(searchKeyword.value));
});

// 搜索事件处理
const onSearch = () => {

};

// 点击考试进入详情页面
const goToDetail = (exam) => {
  if(Local.get('userInfo').role === 2 || Local.get('userInfo').role === 3){
    router.push({
      name: 'scoresparstu',
      query: {
        examId: exam.id, // 将选中的考试的 ID 传递给 scoresParStuDetail 页面
        examName: exam.title
      }
    });
  }else{
    router.push({
      name: 'scoresdetail',
      query: {
        examId: exam.id, // 将选中的考试的 ID 传递给 scoresdetail 页面
        examName: exam.title
      }
    });
  }

};
const confirmDelete = (id) => {
  Dialog.confirm({
    title: '删除考试',
    message: '确定要删除这项考试吗？',
  })
      .then(async () => { // 使用 async 以便使用 await
        try {
          const response = await axios.delete(`/api/exams/delete/${id}`);
          if (response.status === 200) {
            // 从列表中移除考试
            exams.value = exams.value.filter(exam => exam.id !== id);
            Dialog.alert({
              title: '删除成功',
            });
            fetchExams(); // 重新获取考试列表
          } else {
            Dialog.alert({
              title: '删除失败',
              message: '未知错误',
            });
          }
        } catch (error) {
          console.error('Delete failed:', error);
          Dialog.alert({
            title: '错误',
            message: '删除时发生错误，请稍后重试。',
          });
        }
      })
      .catch(() => {
        // 用户点击取消
      });
};

</script>

<style scoped>
.home {
  padding: 20px;
}

.exam-list {
  margin-top: 20px;
  border: 1px solid #ddd;
}

.delete-wrapper {
  display: flex;
  align-items: center;
  justify-content: right;
}
.title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-icon {
  cursor: pointer;
  height: 20px;
  /* 可以添加更多样式 */
}
</style>
